package com.sojson.serversocket.config.handler;

import org.springframework.stereotype.Component;

import com.sojson.serversocket.util.ServerSocketUtil;
import com.sojson.util.HexUtil;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

/**
 * ServerSocket注册包处理器
 *
 * @author liu
 * @date 2024-05-30
 */
@Slf4j
@Component
public class ServerSocketHandlerRegister {

    public void run(ChannelHandlerContext ctx, String data, String addr, String addrRever) throws Exception {
        // 帧长度
        int len = data.length() / 2;
        // 校验码
        String verifyCode = data.substring((len - 3) * 2, (len - 1) * 2);

        HexUtil.crcVerify(data, verifyCode, ServerSocketUtil.HEAD_REGISTER, (len - 3) * 2);

        // 回复帧
        StringBuilder result = new StringBuilder(ServerSocketUtil.HEAD_REGISTER_RESULT);
        result.append(addr);
        result.append(ServerSocketUtil.END);
        log.info("ServerSocket注册回复: " + result);
        ByteBuf byteBuf = Unpooled.copiedBuffer(HexUtil.parseHex(result.toString()));
        ctx.channel().writeAndFlush(byteBuf);
    }

}